﻿#define _CRT_SECURE_NO_WARNINGS
// ↑ 将本行在代码放在第一行可以避免 scanf的报错问题（仅在VS编译器里）
//【头文件包含】
#include"DoubleList.h"

//【函数定义】
/*链表初始化*/DBLN* DoubleListInit(DBLN* phead)
{
	phead = (DBLN*)malloc(sizeof(DBLN));
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
/*链表新节点创建*/DBLN* DoubleListNodeCreat(DBLNDataType x)
{
	DBLN* newnode= (DBLN*)malloc(sizeof(DBLN));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;

}

/*链表打印*/void DoubleListPrint(DBLN* phead)
{
	assert(phead);
	DBLN* cur = phead->next;
	printf("head");
	while (cur != phead)
	{
		printf("->%d<", cur->data);
		cur = cur->next;
	}
	printf("-head\n");

}
/*链表尾插*/void DoubleListPushBack(DBLN* phead,DBLNDataType x)
{
	/*assert(phead);
	DBLN* tail = phead->prev;
	DBLN* newnode = DoubleListNodeCreat(x);
	tail->next = newnode;
	newnode->next = phead;
	newnode->prev = tail;
	phead->prev = newnode;*/

	//利用-指定位置插入函数
	DoubleListInsert(phead, x);
}
/*链表尾删除*/void DoubleListPopBack(DBLN* phead)
{
	/*assert(phead);
	assert(phead->next != phead);
	DBLN* tail = phead->prev;
	DBLN* newtail = tail->prev;
	newtail->next = phead;
	phead->prev = newtail;
	free(tail); */

	//利用-指定位置删除函数
	DoubleListErase(phead->prev);

}
/*链表头插*/void DoubleListPushFront(DBLN* phead, DBLNDataType x)
{
	/*assert(phead);
	DBLN* head = phead->next;
	DBLN* newnode = DoubleListNodeCreat(x);
	head->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = head;*/

	//利用-指定位置插入函数
	DoubleListInsert(phead->next, x);
}
/*链表头删*/void DoubleListPopFront(DBLN* phead)
{
	/*assert(phead);
	assert(phead->next != phead);
	DBLN* head = phead->next;
	DBLN* newhead = head->next;
	phead->next = newhead;
	newhead->prev = phead;
	free(head);*/

	//利用-指定位置删除函数
	DoubleListErase(phead->next);
}
/*链表节点查询*/DBLN* DoubleListNodeSearch(DBLN* phead, DBLNDataType x)
{
	assert(phead);
	DBLN* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)return cur;
		cur = cur->next;
	}
	return NULL;
}
/*链表指定位置插入*/void DoubleListInsert(DBLN* pos, DBLNDataType x)
{
	assert(pos);
	DBLN* prev = pos->prev;
	DBLN* newnode = DoubleListNodeCreat(x);
	prev->next = newnode;
	pos->prev = newnode;
	newnode->next = pos;
	newnode->prev = prev;
}
/*链表指定位置删除*/void DoubleListErase(DBLN* pos)
{
	assert(pos);
	assert(pos->next != pos);//以保证不删除哨兵位
	DBLN* prev = pos->prev;
	DBLN* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

